package com.own.component.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;

/**
 * NettyServerHandler
 *
 * @author chenxueli
 * @date 2022-06-15 03:14:15
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            ByteBuf in = (ByteBuf) msg;
            int readableBytes = in.readableBytes();
            byte[] bytes = new byte[readableBytes];
            in.readBytes(bytes);
            System.out.println(new String(bytes));
            log.error("服务端接受的消息 : " + msg);
        } finally {
            // 抛弃收到的数据
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
        // 当出现异常就关闭连接
        log.error("", throwable);
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("连接的客户端地址:" + ctx.channel().remoteAddress());
        log.debug("连接的客户端ID:" + ctx.channel().id());
        ctx.writeAndFlush("client" + InetAddress.getLocalHost().getHostName() + "success connected！ \n");
        System.out.println("connection");
        super.channelActive(ctx);
    }

}
